package com.newbie.pet.service;

import com.newbie.pet.model.BaseEntity;
import com.newbie.pet.wrap.DPage;
import com.newbie.pet.wrap.P;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.repository.JpaRepository;

/**
 * 类描述：公共方法
 *
 * @author zhangkailiang
 * @date 2020/5/16
 */
public abstract class AbsBaseService<D extends JpaRepository<E, I>, E extends BaseEntity, I> implements BaseService<D, E, I> {

    @Autowired
    private D d;

    @Override
    public E save(E e) {
        return d.save(e);
    }

    @Override
    public E findOneById(I id) {
        return d.findById(id).get();
    }

    @Override
    public Boolean deleteById(I id) {
        d.deleteById(id);
        return true;
    }

    @Override
    public DPage<E> findPage(P<E> p) {
        Page<E> page;
        if (p.getParam() == null) {
            page = d.findAll(p.getPage().toPage());
        } else {
            page = d.findAll(Example.of(p.getParam()), p.getPage().toPage());
        }

        return DPage.of(p.getPage(), page);
    }

    @Override
    public Boolean updateById(E e) {
        d.save(e);
        return true;
    }
}
